package com.snailct.bpp.commons.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

/**
 * this is a read configuration of properties utils 
 * author:andy
 * modify time：2012-9-8
 */
public class PropertiesConfigUtils {
	private static final PropertiesConfigUtils instance = new PropertiesConfigUtils();
	private File configFile;
	private long lastModifyTime;
	private String fileName = "D:\\work\\corenut-commons\\config.properties";
	private Properties props;
	private PropertiesConfigUtils(){
		if(fileName == null || "".equals(fileName.trim())){
			System.err.println("请传入正确的文件名!");
			throw new RuntimeException("请输入正确的文件名");
		}
		configFile = new File(fileName);
		lastModifyTime = configFile.lastModified();
		if(lastModifyTime == 0){
			System.err.println(fileName + "文件不存在");
		}
		props = new Properties();
		try {
			props.load(new FileInputStream(configFile));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static PropertiesConfigUtils getInstance(){
		return instance;
	}
	
	public String getValueByKey(String key){
		long newLastModifyTime = configFile.lastModified();
		//被修改过
		if(newLastModifyTime > lastModifyTime){
			props.clear();
			try {
				props.load(new FileInputStream(configFile));
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return props.getProperty(key);
	}

	public static void main(String[] args){
		String name = PropertiesConfigUtils.getInstance().getValueByKey("name");
		System.out.println(name);
	}
}
